import React, { useState, useEffect } from 'react';
import { X, PlusCircle, Tag } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { useTranslations } from 'next-intl';
// import { updateProjectField } from '@/api/project';

interface KeywordManagerProps {
  initialKeywords?: string[];
  onKeywordsChange?: (keywords: string[]) => void;
  projectId?: string;
}

// 随机颜色数组，用于给新标签分配颜色
const tagColors = [
  'bg-blue-100 text-blue-800 hover:bg-blue-200',
  'bg-green-100 text-green-800 hover:bg-green-200',
  'bg-purple-100 text-purple-800 hover:bg-purple-200',
  'bg-yellow-100 text-yellow-800 hover:bg-yellow-200',
  'bg-pink-100 text-pink-800 hover:bg-pink-200',
  'bg-indigo-100 text-indigo-800 hover:bg-indigo-200',
];

export default function KeywordManager({ initialKeywords = [], onKeywordsChange, projectId }: KeywordManagerProps) {
  const t = useTranslations('project');
  const commonT = useTranslations('common');
  // 关键词状态
  const [keywords, setKeywords] = useState<string[]>(initialKeywords);
  // 新关键词输入
  const [newKeyword, setNewKeyword] = useState('');
  // 关键词颜色映射
  const [keywordColors, setKeywordColors] = useState<Record<string, string>>({});
  // 是否显示输入框
  const [showInput, setShowInput] = useState(false);
  // 加载状态
  const [isLoading, setIsLoading] = useState(false);

  // 当组件挂载或初始关键词变化时，更新关键词和颜色映射
  useEffect(() => {
    // 更新关键词状态
    setKeywords(initialKeywords);

    // 更新颜色映射
    const colors: Record<string, string> = {};
    initialKeywords.forEach((keyword, index) => {
      colors[keyword] = tagColors[index % tagColors.length];
    });
    setKeywordColors(colors);
  }, [initialKeywords]);

  // 添加关键词
  const handleAddKeyword = () => {
    if (newKeyword.trim()) {
      const newKeywordText = newKeyword.trim();
      // 为新关键词分配颜色
      const newColors = { ...keywordColors };
      newColors[newKeywordText] = tagColors[keywords.length % tagColors.length];
      setKeywordColors(newColors);

      const updatedKeywords = [...keywords, newKeywordText];
      // 设置加载状态
      setIsLoading(true);
      // updateProjectField(projectId || '', 'search_keywords', updatedKeywords).then(() => {
      //   setKeywords(updatedKeywords);
      //   setNewKeyword('');
      //   setShowInput(false); // 添加完关键词后隐藏输入框

      //   // 通知父组件关键词变化
      //   if (onKeywordsChange) {
      //     onKeywordsChange(updatedKeywords);
      //   }
      // }).finally(() => {
      //   // 无论成功失败，都结束加载状态
      setIsLoading(false);
      // })
    }
  };

  // 切换显示输入框
  const toggleInput = () => {
    setShowInput(true);
    // 输入框显示后自动聚焦
    setTimeout(() => {
      const inputElement = document.getElementById('new-keyword-input');
      if (inputElement) {
        inputElement.focus();
      }
    }, 10);
  };

  // 删除关键词
  const handleRemoveKeyword = (keyword: string) => {
    const updatedKeywords = keywords.filter(k => k !== keyword);

    // 设置加载状态
    setIsLoading(true);
    // 关闭输入框
    setShowInput(false);

    // 调用API更新数据库
    // updateProjectField(projectId || '', 'search_keywords', updatedKeywords)
    //   .then(() => {
    //     setKeywords(updatedKeywords);

    //     // 通知父组件关键词变化
    //     if (onKeywordsChange) {
    //       onKeywordsChange(updatedKeywords);
    //     }
    //   })
    //   .finally(() => {
    //     // 无论成功失败，都结束加载状态
    //     setIsLoading(false);
    //   });
  };

  // 编辑关键词（双击标签触发）
  const handleEditKeyword = (oldKeyword: string, newLabel: string) => {
    if (newLabel.trim()) {
      const updatedKeywords = keywords.map(keyword =>
        keyword === oldKeyword ? newLabel.trim() : keyword
      );

      // 设置加载状态
      setIsLoading(true);

      // 调用API更新数据库
      // updateProjectField(projectId || '', 'search_keywords', updatedKeywords)
      //   .then(() => {
      //     setKeywords(updatedKeywords);

      //     // 更新颜色映射
      //     const newColors = { ...keywordColors };
      //     newColors[newLabel.trim()] = keywordColors[oldKeyword] || tagColors[0];
      //     setKeywordColors(newColors);

      //     // 通知父组件关键词变化
      //     if (onKeywordsChange) {
      //       onKeywordsChange(updatedKeywords);
      //     }
      //   })
      //   .finally(() => {
      //     // 无论成功失败，都结束加载状态
      //     setIsLoading(false);
      //   });
    }
  };

  // 编辑状态
  const [editingKeyword, setEditingKeyword] = useState<string | null>(null);
  const [editValue, setEditValue] = useState('');

  // 开始编辑关键词
  const startEditing = (keyword: string) => {
    setEditingKeyword(keyword);
    setEditValue(keyword);
    // 编辑框显示后自动聚焦
    setTimeout(() => {
      const inputElement = document.getElementById('edit-keyword-input');
      if (inputElement) {
        inputElement.focus();
      }
    }, 10);
  };

  // 保存编辑
  const saveEdit = () => {
    if (editingKeyword && editValue.trim()) {
      handleEditKeyword(editingKeyword, editValue.trim());
      setEditingKeyword(null);
    }
  };

  // 取消编辑
  const cancelEdit = () => {
    setEditingKeyword(null);
  };

  return (
    <div className="flex items-center gap-2 flex-wrap pt-5">
      {/* 关键词标签列表 */}
      {keywords.length === 0 ? (
        <div className="text-sm text-muted-foreground flex items-center gap-1">
          <Tag className="h-4 w-4" />
          {t('noKeywords')}
        </div>
      ) : (
        keywords.map((keyword) => (
          editingKeyword === keyword ? (
            <div key={keyword} className="flex gap-1 min-w-[150px]">
              <Input
                id="edit-keyword-input"
                value={editValue}
                onChange={(e) => setEditValue(e.target.value)}
                className="h-8 py-1 px-2 text-sm"
                onKeyDown={(e) => {
                  if (e.key === 'Enter') {
                    saveEdit();
                  } else if (e.key === 'Escape') {
                    cancelEdit();
                  }
                }}
                autoFocus
              />
            </div>
          ) : (
            <div
              key={keyword}
              className={`${keywordColors[keyword] || 'bg-gray-100'} rounded-full px-3 py-1 text-sm flex items-center gap-1 cursor-pointer`}
              onDoubleClick={() => startEditing(keyword)}
            >
              <span>{keyword}</span>
              <button
                type="button"
                className="ml-1 rounded-full hover:bg-red-100 h-4 w-4 flex items-center justify-center"
                onClick={() => handleRemoveKeyword(keyword)}
              >
                <X className="h-3 w-3 text-gray-500 hover:text-red-500" />
              </button>
            </div>
          )
        ))
      )}

      {/* 添加新关键词 */}
      {showInput ? (
        <div className="flex gap-2 min-w-[200px]">
          <Input
            id="new-keyword-input"
            value={newKeyword}
            onChange={(e) => setNewKeyword(e.target.value)}
            placeholder={t('addKeywordPlaceholder')}
            className="flex-1"
            onKeyDown={(e) => {
              if (e.key === 'Enter') {
                handleAddKeyword();
              } else if (e.key === 'Escape') {
                setShowInput(false);
                setNewKeyword('');
              }
            }}
            autoFocus
          />
          <Button
            size="sm"
            onClick={handleAddKeyword}
            disabled={isLoading}
            className="flex items-center gap-1 whitespace-nowrap"
          >
            {isLoading ? (
              <>
                <svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                {commonT('loading')}
              </>
            ) : (
              <>
                <PlusCircle className="h-4 w-4" />
                {commonT('add')}
              </>
            )}
          </Button>
        </div>
      ) : (
        <Button
          variant="outline"
          size="sm"
          onClick={toggleInput}
          disabled={isLoading}
          className="flex items-center gap-1 whitespace-nowrap"
        >
          {isLoading ? (
            <>
              <svg className="animate-spin -ml-1 mr-2 h-4 w-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              {commonT('loading')}
            </>
          ) : (
            <>
              <PlusCircle className="h-4 w-4" />
              {t('addKeyword')}
            </>
          )}
        </Button>
      )}
    </div>
  );
}
